<?php

namespace app\purchase\logic;

use think\facade\Db;
use app\api\logic\UploadTestLogic;

class PurchaseSuggestLogic extends BasicLogic
{

    /**
     * @desc   获取采购订单列表接口
     * @author luckyXiong
     * @date   2025-03-21
     */
    public function getSuggestList($params=[]){
        $limit             = getIsset($params,'limit',20);
        $spu               = getIsset($params,'spu');
        $seller_sku        = getIsset($params,'seller_sku');
        $operate_id        = getIsset($params,'operate_id');
        $supply_id         = getIsset($params,'supply_id');
        $purchase_status   = getIsset($params,'purchase_status');
        $create_time       = getIsset($params,'create_time');
        $where             = [];

        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
        }

        if($purchase_status){
            $where[] = ['purchase_status', '=',$purchase_status];
        }

        if($seller_sku){
            $where[] = ['seller_sku', 'like', '%' . $seller_sku . '%'];
        }

        $where[] = ['suggest_quantity', '>',0];

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if($operate_id){
            $where[] = ['operate_id', '=',$operate_id];
        }

        if($supply_id){
            $where[] = ['supply_id', '=',$supply_id];
        }


        $field = '*';
        $res   = Db::name('purchase_stock_suggest')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        $operater_ids  = array_column($list,'operate_id');

        //批量获取创建人;
        $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
        $admin_users_map = array_column($admin_users,null,'id');


        //批量获取图片地址;
        $sku_info        = array_column($list,'seller_sku');
        $skus            = [];
        //批量查看是否1688图片地址;
        $supply_ids      = array_column($list,'supply_id');
        $supply_info     = Db::name('supply')->field('id,is_1688')->whereIn('id',$supply_ids)->select()->toArray();
        $supply_ids_map  = array_column($supply_info,'id');
        foreach($sku_info as $sku){
            if(strpos($sku, '+')!== false){
                    continue;
            }
            $lastSlashPosition = strpos($sku, '/');
            if ($lastSlashPosition !== false) {
                $sku = substr($sku, 0, $lastSlashPosition); // 保留 / 之前的部分
            }
            $skus[] = $sku;
        }
        $sku_image_info  = Db::name('product_seller_sku')->field('id,seller_sku,image_info')->whereIn('seller_sku',$skus)->select()->toArray();
        $image_infos_map = array_column($sku_image_info,'image_info','seller_sku');
        foreach($list as $k=>$v){
            $lastSlashPosition = strpos($v['seller_sku'], '/');
            if ($lastSlashPosition !== false) {
                $v['sku'] = substr($sku, 0, $lastSlashPosition); // 保留 / 之前的部分
            }
            $imange_url = $image_infos_map[$v['seller_sku']]??'';
            if(!$imange_url){
                $imange_url = self::get_imange_url($v['spu']);
            }
            if(!$imange_url){
                $imange_url = Config('Logisticskey.product_image_default');
            }
            $is_1688                   = $supply_ids_map[$v['supply_id']]??'';
            $list[$k]['image_url']     = $imange_url;
            $list[$k]['warehouse']     = '武汉江夏仓库';
            $list[$k]['review_price']  = '0.00';
            $list[$k]['is_1688']       = $is_1688['is_1688']??'';
            $list[$k]['day_90_one']    = getRes($v['sku_90days']/90);
            $admin_users_info          = $admin_users_map[$v['operate_id']]??'';
            $list[$k]['operater']      = $admin_users_info['username']??'';
        }

        $list  = get_unique_supply($list);

        $arr   =  $sku_list = [];



        foreach($list as $k=>$v){
            $currents                = current($v);
            $sku_nums                = count($v);
            $sku_quantity            = array_sum(array_column($v,'suggest_quantity'));
            $arr[$k]['supply_name']  = $currents['supply_name'];
            $arr[$k]['sku_nums']     = $sku_nums;
            $arr[$k]['sku_quantity'] = $sku_quantity;
            $arr[$k]['sku_info']     = $v;
        }

        foreach($arr as $v){
            $sku_list[] = $v;
        }
        $data = [
            'list'   => $sku_list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   获取缺货建议列表接口
     * @author luckyXiong
     * @date   2025-03-21
     */
    public function getShortageList($params=[]){
        $limit             = getIsset($params,'limit',20);
        $spu               = getIsset($params,'spu');
        $seller_sku        = getIsset($params,'seller_sku');
        $operate_id        = getIsset($params,'operate_id');
        $supply_id         = getIsset($params,'supply_id');
        $purchase_status   = getIsset($params,'purchase_status');
        $create_time       = getIsset($params,'create_time');
        $where             = [];

        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
        }

        if($purchase_status){
            $where[] = ['purchase_status', '=',$purchase_status];
        }

        if($seller_sku){
            $where[] = ['seller_sku', 'like', '%' . $seller_sku . '%'];
        }

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if($operate_id){
            $where[] = ['operate_id', '=',$operate_id];
        }

        if($supply_id){
            $where[] = ['supply_id', '=',$supply_id];
        }

        $res   =  Db::name('purchase_stock_suggest')->where(function($query) {
            $query->whereRaw('suggest_quantity - safe_quantity > ?', [0])
            ->whereRaw('inventory_quantity + on_way_quantity < sku_1days');
            })
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        $operater_ids  = array_column($list,'operate_id');

        //批量获取创建人;
        $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
        $admin_users_map = array_column($admin_users,null,'id');
        //批量获取图片地址;
        $sku_info        = array_column($list,'seller_sku');
        $skus            = [];
        //批量查看是否1688图片地址;
        $supply_ids      = array_column($list,'supply_id');
        $supply_info     = Db::name('supply')->field('id,is_1688')->whereIn('id',$supply_ids)->select()->toArray();
        $supply_ids_map  = array_column($supply_info,'id');
        foreach($sku_info as $sku){
            if(strpos($sku, '+')!== false){
                continue;
            }
            $lastSlashPosition = strpos($sku, '/');
            if ($lastSlashPosition !== false) {
                $sku = substr($sku, 0, $lastSlashPosition); // 保留 / 之前的部分
            }
            $skus[] = $sku;
        }
        $sku_image_info  = Db::name('product_seller_sku')->field('id,seller_sku,image_info')->whereIn('seller_sku',$skus)->select()->toArray();
        $image_infos_map = array_column($sku_image_info,'image_info','seller_sku');
        foreach($list as $k=>$v){
            $lastSlashPosition = strpos($v['seller_sku'], '/');
            if ($lastSlashPosition !== false) {
                $v['sku'] = substr($sku, 0, $lastSlashPosition); // 保留 / 之前的部分
            }
            $imange_url = $image_infos_map[$v['seller_sku']]??'';
            if(!$imange_url){
                $imange_url = self::get_imange_url($v['spu']);
            }
            if(!$imange_url){
                $imange_url = Config('Logisticskey.product_image_default');
            }
            $is_1688                      = $supply_ids_map[$v['supply_id']]??'';
            $list[$k]['imange_url']       = $imange_url;
            $list[$k]['warehouse']        = '武汉江夏仓库';
            $list[$k]['is_1688']          = $is_1688['is_1688']??'1';
            $admin_users_info             = $admin_users_map[$v['operate_id']]??'';
            $list[$k]['operater']         = $admin_users_info['username']??'';
            $list[$k]['suggest_quantity'] = $v['suggest_quantity']-$v['safe_quantity'];
        }

        $list  = get_unique_supply($list);

        $arr   =  $sku_list = [];

        foreach($list as $k=>$v){
            $currents                = current($v);
            $sku_nums                = count($v);
            $sku_quantity            = array_sum(array_column($v,'suggest_quantity'));
            $arr[$k]['supply_name']  = $currents['supply_name'];
            $arr[$k]['sku_nums']     = $sku_nums;
            $arr[$k]['sku_quantity'] = $sku_quantity;
            $arr[$k]['sku_info']     = $v;
        }

        foreach($arr as $v){
            $sku_list[] = $v;
        }
        $data = [
            'list'   => $sku_list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    private function get_imange_url($spu=''){
        return Db::name('product_seller_sku')->where(['spu'=>$spu])->value('image_info');
    }


    /**
     * @desc   暂不采购
     * @author luckyXiong
     * @date   2024-12-21
     */
    public function unPurchase($params=[]){
           $id = $params['id']??'';
           Db::name('purchase_stock_suggest')->where(['id'=>$id])->update(
               [
                    'purchase_status'=>2,
                    'update_time'    =>date("Y-m-d H:i:s", time()),
               ]
           );
           return  $this->jsonMessage(200,true,'操作成功','');
    }


    /**
     * @desc   添加备注接口
     * @author luckyXiong
     * @date   2024-12-21
     */
    public function addRemark($params=[]){
        $id           = $params['id']??'';
        $remark       = $params['remark']??'';
        $remark_color = $params['remark_color']??'';
        Db::name('purchase_stock_suggest')->where(['id'=>$id])->update(
            [
                'remark'        =>$remark,
                'remark_color' =>$remark_color,
                'update_time'  =>date("Y-m-d H:i:s", time()),
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功','');
    }


    /**
     * @desc   更换供货商接口
     * @author luckyXiong
     * @date   2024-12-21
     */
    public function changeSupply($params=[]){
           $id          = $params['id']??'';
           $supply_id   = $params['supply_id']??'';
           $supply_name = Db::name('supply')->where(['id'=>$supply_id])->value('supply_name');
           Db::name('purchase_stock_suggest')->where(['id'=>$id])->update(
            [
                'supply_id'    =>$supply_id,
                'supply_name'  =>$supply_name,
                'update_time'  =>date("Y-m-d H:i:s", time()),
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功','');
    }


    /**
     * @desc   更改采购数量
     * @author luckyXiong
     * @date   2025-03-21
     */
    public function update_purchase_quantity($params=[]){
        $id                    = $params['id']??'';
        $purchase_quantity     = $params['purchase_quantity']??'';
        Db::name('purchase_stock_suggest')->where(['id'=>$id])->update(
            [
                'purchase_quantity'=>$purchase_quantity,
                'update_time'      =>date("Y-m-d H:i:s", time()),
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功','');
    }


    /**
     * @desc   加入采购计划接口
     * @author luckyXiong
     * @date   2025-03-21
     */
    public function removePlan($params=[]){
            $id         = $params['id']??'';
            //获取当前的采购数量;
            $field      = '*';
            $suggests   =  Db::name('purchase_stock_suggest')->field($field)->where(['id'=>$id])->find();
            //更新缺货建议表的建议数量;
            Db::name('purchase_stock_suggest')->where(['id'=>$id])
            ->dec('suggest_quantity',$suggests['purchase_quantity'])
            ->inc('pre_suggest_quantity',$suggests['purchase_quantity'])
            ->update();
            //同时采购计划表插入一条记录;
            $exist_purchase_plan = Db::name('purchase_plan')
                                   ->where(['seller_sku'=>$suggests['seller_sku']])
                                   ->find();
            if($exist_purchase_plan){
                  Db::name('purchase_plan')
                    ->where(['seller_sku'=>$suggests['seller_sku']])
                    ->inc('purchase_nums',$suggests['purchase_quantity'])
                    ->update();
            }else{
                //查看当前的厂家是否1688
                $is_1688  = Db::name('supply')->where(['id'=>$suggests['supply_id']])->value('is_1688');
                if($is_1688==1){
                    $info_1688 = Db::name('product_1688')->where(['seller_sku'=>$suggests['seller_sku']])->find();
                }
                //写入一条新记录;
                $insert_info = [
                           'seller_sku'         => $suggests['seller_sku'],
                           'image_url'          => $suggests['image_url']??'',
                           '1688_product_id'    => $info_1688['1688_product_id']??'',
                           '1688_product_image' => $info_1688['1688_product_image']??'',
                           '1688_product_url'   => $info_1688['1688_product_url']??'',
                           '1688_product_name'  => $info_1688['1688_product_name']??'',
                           'varient_colour'     => $info_1688['varient_colour']??'',
                           'varient_size'       => $info_1688['varient_size']??'',
                           'specId'             => $info_1688['specId']??'',
                           'purchase_price'     => $suggests['purchase_price']??'',
                           'purchase_nums'      => $suggests['purchase_quantity']??'',
                           'operate_id'         => $suggests['operate_id']??'',
                           'supply_id'          => $suggests['supply_id']??'',
                           'is_1688'            => $is_1688??'',
                           'supply_name'        => $suggests['supply_name']??'',
                           'update_time'        =>date("Y-m-d H:i:s", time()),
                           'create_time'        =>date("Y-m-d H:i:s", time()),
                        ];
                Db::name('purchase_plan')->insert($insert_info);
            }
        return  $this->jsonMessage(200,true,'操作成功','');
    }


    /**
     * @desc   获取采购计划列表
     * @author luckyXiong
     * @date   2025-03-21
     */
    public function suggestPlan($params=[]){
        $limit             = getIsset($params,'limit',20);
        $ids               = $params['ids']??[];
        $seller_sku        = getIsset($params,'seller_sku');
        $supply_id         = getIsset($params,'supply_id');
        $is_1688           = getIsset($params,'is_1688');
        $where = [];
        if($ids){
            $where[] = ['id', 'in',$ids];
        }

        if($seller_sku){
            $where[] = ['seller_sku', '=',$seller_sku];
        }

        if($supply_id){
            $where[] = ['supply_id','=',$supply_id];
        }

        if($is_1688){
            $where[] = ['is_1688', '=',$is_1688];
        }


        $res   = Db::name('purchase_plan')
            ->field("*")
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        $operater_ids  = array_column($list,'operate_id');

        //批量获取创建人;
        $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
        $admin_users_map = array_column($admin_users,null,'id');

        foreach($list as $k=>$v){
            $admin_users_info          = $admin_users_map[$v['operate_id']]??'';
            $list[$k]['operater']      = $admin_users_info['username']??'';
        }
        $list  = get_unique_supply($list);
        $arr   =  $sku_list = [];
        foreach($list as $k=>$v){
            $currents                = current($v);
            $arr[$k]['supply_name']  = $currents['supply_name'];
            $arr[$k]['sku_info']     = $v;
        }
        foreach($arr as $v){
            $sku_list[] = $v;
        }
        $data = [
            'list'   => $sku_list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }



    /**
     * @desc   获取购物车列表接口
     * @author luckyXiong
     * @date   2025-03-21
     */
    public function carPlan($params=[]){
        $where  = $info = [];
        $list   = Db::name('purchase_plan')
            ->field("*")
            ->where($where)
            ->order('create_time desc')
            ->select()
            ->toArray();

        foreach($list as $k=>$v){
            $info[$k]['id']             = $v['id']??'';
            $info[$k]['is_1688']        = $v['is_1688']??'';
            $info[$k]['seller_sku']     = $v['seller_sku']??'';
            $info[$k]['image_url']      = $v['image_url']??'';
            $info[$k]['purchase_price'] = $v['purchase_price']??'';
            $info[$k]['purchase_nums']  = $v['purchase_nums']??'';
            $info[$k]['supply_name']    = $v['supply_name']??'';
            $info[$k]['supply_id']      = $v['supply_id']??'';

        }
        $info  = get_unique_supply($info);
        $arr   =  $sku_list = [];
        foreach($info as $k=>$v){
            $currents                = current($v);
            $arr[$k]['supply_name']  = $currents['supply_name'];
            $arr[$k]['sku_info']     = $v;
        }
        foreach($arr as $v){
            $sku_list[] = $v;
        }
        $data = [
            'list'   => $sku_list,
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   购物车删除数据接口
     * @author luckyXiong
     * @date   2025-03-21
     */
    public function delPlan($params=[]){
           $id               = $params['id']??'';
           $info             = Db::name('purchase_plan')->where(['id'=>$id])->find();
           //更新备货计划表的采购数量和采购建议数量字段;
           $suggest_quantity = self::get_suggest_quantity($info['seller_sku'],0);
           Db::name('purchase_stock_suggest')->where(['seller_sku'=>$info['seller_sku']])
            ->update(
                [
                    'suggest_quantity'    =>$suggest_quantity,
                    'pre_suggest_quantity'=>0
                ]
            );
           Db::name('purchase_plan')->where(['id'=>$id])->delete();
           return  $this->jsonMessage(200,true,'操作成功',null);
    }



    /**
     * @desc   获取备货建议中的建议数量
     * @author luckyXiong
     * @date   2025-03-24
     */
    public function get_suggest_quantity($seller_sku,$plan_quantity=0){
        $field        = 'seller_sku,sku_1days,safe_quantity,on_way_quantity,inventory_quantity';
        $suggest_info = Db::name('purchase_stock_suggest')->field($field)->where(['seller_sku'=>$seller_sku])->find();
        $suggest_nums = 0;
        if(!$plan_quantity){
            $plan_quantity=0;
        }
        if($suggest_info){
            //建议数量 = （订单量 + 安全库存 ） - （在途 + 库存 ）- 采购计划中
            $suggest_nums = $suggest_info['sku_1days'] + $suggest_info['safe_quantity']-($suggest_info['on_way_quantity']+$suggest_info['inventory_quantity'])-$plan_quantity;
        }
        return  $suggest_nums;
    }





    /**
     * @desc   购物车修改数据接口
     * @author luckyXiong
     * @date   2025-03-24
     */
    public function editPlan($params=[]){
            $id           = $params['id']??'';
            $planNumber   = $params['planNumber']??'';
            $info         = Db::name('purchase_plan')->where(['id'=>$id])->find();
            $suggest_quantity = self::get_suggest_quantity($info['seller_sku'],$planNumber);
            //确认字段大小;
            $edit_suggest_quantity = $suggest_quantity;
            if($suggest_quantity< 0){
                //更新备货计划表的采购数量和采购建议数量字段;
                $edit_suggest_quantity = 0;
            }
            Db::name('purchase_stock_suggest')
                ->where(['seller_sku'=>$info['seller_sku']])
               ->update(
                [
                    'suggest_quantity'     => $edit_suggest_quantity,
                    'pre_suggest_quantity' => $planNumber,
                    'update_time'          => date("Y-m-d H:i:s", time()),
                ]
            );
            Db::name('purchase_plan')->where(['id'=>$id])->update(
               [
                   'purchase_nums' => $planNumber,
                   'update_time'   => date("Y-m-d H:i:s", time())
               ]
           );
           return  $this->jsonMessage(200,true,'操作成功',null);
     }



    /**
     * @desc   购物车配对保存接口
     * @author luckyXiong
     * @date   2025-03-24
     */
    public function addPlanSku($params=[]){
        $specId     = $params['specId']??'';
        $id         = $params['id']??'';
        $info_1688  = Db::name('product_1688')->where(['specId'=>$specId])->find();
        $update_info  = [
            '1688_product_id'    => $info_1688['1688_product_id']??'',
            '1688_product_image' => $info_1688['1688_product_image']??'',
            '1688_product_url'   => $info_1688['1688_product_url']??'',
            '1688_product_name'  => $info_1688['1688_product_name']??'',
            'varient_colour'     => $info_1688['varient_colour']??'',
            'varient_size'       => $info_1688['varient_size']??'',
            'specId'             => $info_1688['specId']??'',
            'update_time'        => date("Y-m-d H:i:s", time()),
        ];
        Db::name('purchase_plan')->where(['id'=>$id])->update($update_info);
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    /**
     * @desc   更换操作人
     * @author luckyXiong
     * @date   2025-03-24
     */
    public function editOperater($params=[]){
        $operate_id    = $params['operate_id']??'';
        $id            = $params['id']??'';
        $update_info = [
            'operate_id'         => $operate_id,
            'update_time'        => date("Y-m-d H:i:s", time()),
        ];
        Db::name('purchase_plan')->where(['id'=>$id])->update($update_info);
        return  $this->jsonMessage(200,true,'操作成功',null);
    }


    /**
     * @desc   购物车提交采购单详情接口
     * @author luckyXiong
     * @date   2025-03-24
     */
    public function purchaseDetail($params=[]){
        $ids      =  $params['ids']??'';
        $admin_id =  $params['admin_id']??'';
        $where    = $skus = $info_list = [];
        if($ids){
            $where[] = ['id', 'in',$ids];
        }
        $field  = 'id,seller_sku,image_url,1688_product_id,1688_product_image,1688_product_url,1688_product_name,
                  is_1688,varient_colour,remark,operate_id,remark_color,varient_size,specId,purchase_price,purchase_nums,supply_id,supply_name';
        $list   = Db::name('purchase_plan')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->select()
            ->toArray();
        foreach($list as $v){
            if(!$v['specId'] && $v['is_1688']==1){
                $skus[]      = $v['seller_sku'];
            }else{
                $info_list[] = $v;
            }
        }
        if(!$info_list){
            $skus    = implode(',',$skus);
            $message = 'sku商品'.$skus.'未完成1688配对!请先1688配对!';
            return  $this->jsonMessage(201,false,$message,null);
        }

        $list  = get_unique_supply($info_list);
        $arr   =  $sku_list = [];
        $account_info = Db::name('1688_token')->order('id asc')->find();
        foreach($list as $k=>$v){
            $currents                = current($v);
            $arr[$k]['supply_name']  = $currents['supply_name'];
            $arr[$k]['is_1688']      = $currents['is_1688'];
            $arr[$k]['supply_id']    = $currents['supply_id'];
            $arr[$k]['operate_id']   = $currents['operate_id'] ? : $admin_id;
            $arr[$k]['track_fee_type'] = 1;
            $arr[$k]['remark']       = $currents['remark'];
            $arr[$k]['remark_color'] = $currents['remark_color'];
            if($currents['is_1688']==1){ // 1688
                $arr[$k]['account_1688'] = $account_info['account_1688'];
                $arr[$k]['address']      = $account_info['address'];
                $arr[$k]['1688_remark']  = '';
            }
            $arr[$k]['sku_info']     = $v;
        }
        foreach($arr as $v){
            $sku_list[] = $v;
        }
        $data = [
            'list'   => $sku_list,
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   购物车采购单写入采购主表
     * @author luckyXiong
     * @date   2025-03-25
     */
    public function purchaseSubmit($params){
        $sku_list       = $params['sku_list']??'';
        foreach($sku_list as $v){
                self::add_purchase($v);
        }
        return  $this->jsonMessage(200,true,'操作成功',null);
    }


    //详情提数据入库处理
    private function add_purchase($params=[]){
        $purchase_number = getPurchaseNumber();
        $purchase_info   = [];
        $purchase_detail = $params['sku_info']??'';
        $supply_id       = $params['supply_id']??'';
        $remark          = $params['remark']??'';
        $remark_color    = $params['remark_color']??'';
        $operater_id     = $params['operater_id']??'';
        $account_1688    = $params['account_1688']??'';
        $is_1688         = $params['is_1688']??'1';
        $message_1688_remark  = $params['1688_remark']??'';
        foreach($purchase_detail as $v){
            $spu_info                    = explode('-', $v['seller_sku']);
            $spu                         = $spu_info[0]??'';
            $temp['purchase_number']     = $purchase_number;
            $temp['spu']                 = $spu;
            $temp['seller_sku']          = $v['seller_sku']??'';
            $temp['purchase_price']      = $v['purchase_price']??'';
            $temp['purchase_quantity']   = $v['purchase_nums']??'';
            $temp['purchase_cost']       = $v['purchase_cost']??'';
            $temp['1688_product_id']     = $v['1688_product_id']??'';
            $temp['1688_product_image']  = $v['1688_product_image']??'';
            $temp['1688_product_url']    = $v['1688_product_url']??'';
            $temp['1688_product_name']   = $v['1688_product_name']??'';
            $temp['varient_colour']      = $v['varient_colour']??'';
            $temp['varient_size']        = $v['varient_size']??'';
            $temp['specId']              = $v['specId']??'';
            $temp['image_url']           = $v['image_url']??'';
            $temp['update_time']         = date('Y-m-d H:i:s',time());
            $temp['create_time']         = date('Y-m-d H:i:s',time());
            $purchase_info[]             = $temp;
        }
        $in_stores_quantity_all = array_sum(array_column($purchase_detail,'purchase_nums'));
        $purchase_price_all     = array_sum(array_column($purchase_detail,'purchase_price'));
        //采购主表spu信息统计;
        $spus              = array_unique(array_column($purchase_info,'spu'));
        if($is_1688==1){
            $order_1688_number = $account_1688.'-'.random_int(1000, 99999);
        }else{
            $order_1688_number = '';
        }

        $supply_info = Db::name('supply')->where(['id'=>$supply_id])->find();
        $current_info = current($purchase_detail);
        $purchase_arr = [
            'purchase_number'   =>$purchase_number,
            'spu'               =>$spus ? implode(',',$spus):'',
            'sku_nums'          =>count($purchase_detail),
            'purchase_cost'     =>$purchase_price_all,
            'warehouse'         =>'武汉江夏仓',
            'supply_id'         =>$supply_id,
            'purchase_quantity' =>$in_stores_quantity_all,
            'remark'            =>$remark,
            'remark_color'      =>$remark_color,
            'purchase_type'     =>$is_1688==1 ? 2 :1,
            '1688_account'      =>$account_1688,
            '1688_remark'       =>$message_1688_remark,
            '1688_order_number' =>$order_1688_number,
            '1688_openUid'      =>$supply_info['user_id']??'',
            '1688_wangwang_url' =>$supply_info['1688_wangwang_url']??'',
            'track_fee_type'    =>$track_fee_type??'1',
            'operater_id'       =>$operater_id,
            'image_url'         =>$current_info['image_url']??'',
            'update_time'       =>date('Y-m-d H:i:s',time()),
            'create_time'       =>date('Y-m-d H:i:s',time()),
        ];

        try {
            Db::startTrans(); // 开启事务
            Db::name('purchase_manual')->insert($purchase_arr);
            Db::name('purchase_manual_detail')->insertAll($purchase_info);
            Db::commit(); // 提交事务
            $this->jsonMessage(200,true,'操作成功',null);
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }
    }












}